"""
数据库配置模块
使用SQLAlchemy 2.0 ORM配置数据库连接和会话管理
"""

import logging
from sqlalchemy import create_engine, text
from sqlalchemy.orm import sessionmaker, declarative_base
from sqlalchemy.pool import QueuePool
from src.utils.logging import get_logger

# Type annotation to help Pylance understand the type
from typing import TYPE_CHECKING
if TYPE_CHECKING:
    from src.config.settings import Settings
    settings: Settings  # type annotation only

logger = get_logger(__name__)

# 延迟导入settings以避免循环导入
def get_settings():
    from src.config.settings import settings
    return settings

# 创建声明式基类
Base = declarative_base()

# 数据库引擎和会话配置
def get_database_url():
    return get_settings().DATABASE_URL

def get_engine():
    # 使用延迟导入避免循环依赖
    settings = get_settings()
    return create_engine(
        settings.DATABASE_URL,
        poolclass=QueuePool,
        pool_size=settings.DATABASE_POOL_SIZE,
        max_overflow=settings.DATABASE_MAX_OVERFLOW,
        pool_timeout=settings.DATABASE_POOL_TIMEOUT,
        pool_recycle=settings.DATABASE_POOL_RECYCLE,
        echo=settings.DATABASE_ECHO
    )

# 延迟初始化引擎实例
_engine = None

def get_initialized_engine():
    global _engine
    if _engine is None:
        _engine = get_engine()
    return _engine

# 延迟初始化SessionLocal
_SessionLocal = None

def get_session_local():
    global _SessionLocal
    if _SessionLocal is None:
        _SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=get_initialized_engine())
    return _SessionLocal

# 数据库依赖项
def get_db():
    db = get_session_local()()
    try:
        yield db
    finally:
        db.close()

# 初始化数据库
def init_db():
    # 在这里导入所有模型以确保它们在创建表之前被加载
    from src.models.ticket import Ticket
    from src.models.user import User
    from src.models.group import Group
    from src.models.session import Session
    from src.models.project import Project
    from src.models.user_preference import UserPreference
    
    # 创建所有表
    Base.metadata.create_all(bind=get_initialized_engine())

def init_database():
    """初始化数据库的别名"""
    init_db()

def drop_db():
    """删除所有表"""
    from src.models.ticket import Ticket
    from src.models.user import User
    from src.models.group import Group
    from src.models.session import Session
    from src.models.project import Project
    from src.models.user_preference import UserPreference
    
    Base.metadata.drop_all(bind=get_initialized_engine())

def check_db_health():
    """检查数据库连接状态"""
    try:
        db = get_session_local()()
        db.execute(text("SELECT 1"))
        db.close()
        return True
    except Exception as e:
        logger.error(f"数据库连接检查失败: {e}")
        return False